﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.UI;

public class GameManager : MonoBehaviour {

    [SerializeField]
    private TextMeshProUGUI displayTiming;
    [SerializeField]
    private Camera mainCamera;

    private int remianTime;
    public bool isPass;
    private GameObject player;

    private void InitPlayer()
    {
        GameObject playerInPrefab = Resources.Load("player") as GameObject;
        Transform bornPoint = GameObject.Find("Start").transform;
        player = Instantiate(playerInPrefab,
            new Vector2(bornPoint.position.x, bornPoint.position.y + 2), Quaternion.identity);
    }

    private void Timer()
    {
        displayTiming.text = "10";
        remianTime = int.Parse(displayTiming.text);
        InvokeRepeating("CountTime", 1, 1);
    }

    private void CountTime()
    {
        if (remianTime == 0)
        {
            CancelInvoke();
            if (!isPass)
            {
                Debug.Log("游戏失败");
                Time.timeScale = 0;
            }
        }
        else
        {
            remianTime -= 1;
            displayTiming.text = remianTime.ToString();
        }
    }

    private void CameraFollow()
    {
        float x = player.transform.position.x;
        float y = player.transform.position.y;
        mainCamera.transform.position = new Vector3(x, y, -10);
    }

    // Use this for initialization
    void Start () {
        isPass = false;
        Timer();
        InitPlayer();
	}
	
	// Update is called once per frame
	void Update () {
        if (isPass)
        {
            Debug.Log("恭喜过关");
            CancelInvoke();
            Time.timeScale = 0;
        }
	}

    private void LateUpdate()
    {
        CameraFollow();
    }

    public void setIsPass(bool isPass)
    {
        this.isPass = isPass;
    }

}
